<template>
  <div class="form-wrapper">

    <el-form :model="loginForm" label-width="70px" class="form-content">
      <h1>登录页面</h1>
      <!-- 表单项 -->
      <el-form-item label="用户名">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="loginForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form-item>
      <div class="switch-link">
        没有账号？
        <el-link type="primary" @click="goRegister">去注册</el-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { loginUser } from '@/api/user';

const loginForm = reactive({
  username: '',
  password: ''
});

const router = useRouter();

const handleLogin = async () => {
  if (!loginForm.username || !loginForm.password) {
    ElMessage.warning('请输入用户名和密码');
    return;
  }

  try {
    const response = await loginUser({
      username: loginForm.username,
      passwordHash: loginForm.password
    });

    // 后端返回的是 { message, userId, username, avatarUrl, token }
    const { message, userId, username, nickname, email, avatarUrl, token } = response.data;

    // 保存到本地存储
    localStorage.setItem('token', token);
    localStorage.setItem('username', username);
    localStorage.setItem('nickname', nickname);
    localStorage.setItem('userId', userId);
    localStorage.setItem('email', email);
    localStorage.setItem('avatarUrl', avatarUrl);
    ElMessage.success(message || '登录成功');
    await router.push('/home'); // 跳转到主页
  } catch (error) {
    ElMessage.error(error.response ? error.response.data : '登录失败');
  }
};


const goRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.form-wrapper {
  height: 80vh; /* 占屏幕高度80% */
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.form-content {
  width: 360px; /* 固定宽度 */
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  padding: 30px 40px;
  border-radius: 8px;
  background: #fff;
}
.switch-link {
  margin-top: 10px;
  font-size: 14px;
  text-align: center;
}
</style>
